package com.android.happymall.fragment.member;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.happymall.activity.mine.TransparentActivity;
import com.android.happymall.model.data;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.fragment.BaseLazyFragment;
import com.android.happymall.model.dataCallback;
import com.android.happymall.model.member.AddressListDataCallback;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.MyLog;
import com.android.happymall.view.dialog.MainMsg;
import com.android.happymall.R;
import com.android.happymall.model.member.AddressListData;
import com.android.happymall.utils.LoginState;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 收货地址
 */
public class Fragment_Mine_Address extends BaseLazyFragment {


    @BindView(R.id.listView)
    NestFullListView listView;

    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_address)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private FragmentActivity mcontext;
    private View view;
    private LayoutInflater inflater;

    private static final String ARG_PARAM1 = "param1";
    private String resultid;
    private boolean networkConnected;

    private String getid;
    private String getpd;


    public Fragment_Mine_Address() {


    }


    public static Fragment_Mine_Address newInstance(String param1) {
        Fragment_Mine_Address fragment = new Fragment_Mine_Address();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            resultid = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    protected void initPrepare() {
        initUI();
    }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {


    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_mine_address, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }


    private void initUI() {


        listView.setAdapter(new NestFullListViewAdapter<AddressListData.AddressData>(R.layout.item_list_mine_address, addressdata) {
            @Override
            public void onBind(int position, AddressListData.AddressData addressData, NestFullViewHolder holder) {

               // holder.setOnClickListener(R.id.item_list_mine_address_delete, new ClickUpdateAddress(0, position));
              //  holder.setOnClickListener(R.id.item_list_mine_address_xiugai, new ClickUpdateAddress(1, position));
                holder.setText(R.id.item_list_mine_address_name, addressData.getName() + "(" + addressData.getMobile() + ")");
                holder.setText(R.id.item_list_mine_address_address, addressData.getArea() + addressData.getAddress());
                if (addressData.getIs_default().equals("1")) {
                    holder.setChecked(R.id.item_list_mine_address_check, true);
                } else {
                    holder.setChecked(R.id.item_list_mine_address_check, false);
                }


            }
        });

        listView.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {

                if (addressdata.get(position).getIs_default().equals("1")) {
                    ObjectUtils.toast(mcontext, "已设置为默认地址");
                } else {
                    //设置默认地址
                    setDefault(addressdata.get(position).getId());
                }
            }
        });


    }


    private class ClickUpdateAddress implements View.OnClickListener {
        private int position;
        private int type;

        public ClickUpdateAddress(int type, int position) {
            this.position = position;
            this.type = type;
        }

        @Override
        public void onClick(View view) {
            if (type == 0) {
                final MainMsg mainMsg = new MainMsg(mcontext);
                mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否删除该地址？");
                mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                    @Override
                    public void onSure() {
                        setDetele(addressdata.get(position).getId(), "1", position);
                        mainMsg.close();
                    }
                });
            } else {
                Intent intent = new Intent(mcontext, TransparentActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 1);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NAME, addressdata.get(position).getName());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_PHONE, addressdata.get(position).getMobile());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_CITY, addressdata.get(position).getArea());
            //    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_CITY_ID, addressdata.get(position).getCity_id());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_ADDRESS, addressdata.get(position).getAddress());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_ID, addressdata.get(position).getId());
                startActivity(intent);
            }
        }
    }

    @OnClick({R.id.click_resetnetwork_refresh, R.id.address_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                GetDataListData();
                break;
            case R.id.address_add:
                Intent intent = new Intent(mcontext, TransparentActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        GetDataListData();


    }


    ArrayList<AddressListData.AddressData> addressdata = new ArrayList<>();

    //获取列表数据
    private void GetDataListData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSLIST;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = new HashMap<>();
            getid = LoginState.getInstance().getid(mcontext);
            getpd = LoginState.getInstance().getpd(mcontext);
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new AddressListDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(AddressListData response, int id) {
                            addressdata.clear();
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            if (response.getCode() == 0) {
                                if (response.getData() != null) {
                                    noData.setVisibility(View.GONE);
                                    addressdata.addAll(response.getData());
                                    listView.updateUI();
                                } else {
                                    noData.setVisibility(View.VISIBLE);
                                }
                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }

                        }
                    }

            );
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    //设置默认地址

    private void setDefault(String id) {

        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSDEFAULT + "?id=" + id;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            HashMap<String, String> header = new HashMap<>();
            getid = LoginState.getInstance().getid(mcontext);
            getpd = LoginState.getInstance().getpd(mcontext);
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new dataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    progressLoading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(data response, int id) {
                    progressLoading.setVisibility(View.GONE);
                    if (response.getCode() == 0) {
                        ObjectUtils.toast(mcontext, "设置成功");
                        GetDataListData();
                    } else {
                        ObjectUtils.toast(mcontext, response.getMsg());
                    }
                }
            });
        } else {

            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

    }

    //删除
    private void setDetele(String id, String mid, final int position) {
        progressLoading.setVisibility(View.VISIBLE);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSDETELE + "?mid=" + mid + "&id=" + id;
        HttpUtils.get(address, null, new dataCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                progressLoading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(data response, int id) {
                progressLoading.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, response.getMsg());
                if (response.getCode() == 0) {
                    addressdata.remove(position);
                    listView.updateUI();
                    if (addressdata.size() == 0) {
                        noData.setVisibility(View.VISIBLE);
                    }

                }
            }
        });
    }
}
